package com.starry.module.system.core.logger.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.starry.core.common.domain.vo.PageVo;
import com.starry.core.common.execption.ServiceException;
import com.starry.core.security.context.SecurityInfoContext;
import com.starry.module.system.api.logger.domain.qo.SysLogErrorPageQo;
import com.starry.module.system.api.logger.domain.qo.SysLogErrorProcessingQo;
import com.starry.module.system.api.logger.domain.qo.SysLogErrorQo;
import com.starry.module.system.api.logger.domain.vo.SysLogErrorVo;
import com.starry.module.system.core.logger.entity.SysLogError;
import com.starry.module.system.core.logger.mapper.SysLogErrorMapper;
import com.starry.module.system.core.logger.service.SysLogErrorService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

import static com.starry.core.common.constants.CommonError.DATA_NOT_EXISTS;

/**
 * 异常日志-服务实现
 * @author xiaoke
 */
@Service("sysLogErrorService")
public class SysLogErrorServiceImpl implements SysLogErrorService {

    private final SysLogErrorMapper sysLogErrorMapper;

    public SysLogErrorServiceImpl(SysLogErrorMapper sysLogErrorMapper) {
        this.sysLogErrorMapper = sysLogErrorMapper;
    }

    @Override
    public PageVo<SysLogErrorVo> page(SysLogErrorPageQo pageQo) {
        PageVo<SysLogError> page = sysLogErrorMapper.selectPage(pageQo);
        List<SysLogErrorVo> vos = BeanUtil.copyToList(page.getRows(), SysLogErrorVo.class);
        return new PageVo<>(vos, page.getTotal());
    }

    @Override
    public void processing(SysLogErrorProcessingQo processingQo) {
        SysLogError infraLogError = sysLogErrorMapper.selectById(processingQo.getId());
        if (infraLogError == null) {
            throw new ServiceException(DATA_NOT_EXISTS.getMsg());
        }
        BeanUtil.copyProperties(processingQo, infraLogError);
        infraLogError.setProcessUserId(SecurityInfoContext.getUserId());
        infraLogError.setProcessUserName(SecurityInfoContext.getUsername());
        infraLogError.setProcessTime(LocalDateTime.now());
        sysLogErrorMapper.updateById(infraLogError);
    }

    @Transactional
    @Override
    public Long save(SysLogErrorQo sysLogErrorQo) {
        SysLogError sysLogError = BeanUtil.toBean(sysLogErrorQo, SysLogError.class);
        sysLogError.setId(null);
        sysLogErrorMapper.insert(sysLogError);
        return sysLogError.getId();
    }

    @Transactional
    @Override
    public void removeByIds(Set<Long> idList) {
        if (idList.isEmpty()) return;
        sysLogErrorMapper.deleteByIds(idList);
    }

}

